package com.dcm.pay.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.dcm.pay.config.AlipayConfig;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
/**
 * @author 牛浩
 */
@RestController
@CrossOrigin
public class PayController {

    @GetMapping("/aliapy")
    public void alipay(HttpServletResponse httpResponse,
                       @RequestParam(value = "name",required = false) String name,
                       @RequestParam(value = "price",required = false) double price) throws IOException {

        //实例化客户端,填入所需参数
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(AlipayConfig.return_url);
        request.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String outTradeNo = UUID.randomUUID().toString();
        //付款金额，必填
        double totalAmount =price;
        //订单名称，必填
        String subject =name;
        //商品描述，可空
        String body = name;
        request.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","
                + "\"total_amount\":\""+ totalAmount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            /**
             * 调用SDK生成表单
             */
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.charset);
        /**
         * 直接将完整的表单html输出到页面
         */
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


}
